package com.guigui.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigui.gulimall.order.config.AlipayTemplate;
import com.guigui.gulimall.order.entity.OrderEntity;
import com.guigui.gulimall.order.entity.OrderItemEntity;
import com.guigui.gulimall.order.service.OrderItemService;
import com.guigui.gulimall.order.service.OrderService;
import com.guigui.gulimall.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class WebOrderPayController {

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @GetMapping(value = "/payOrder", produces = {"text/html"})
    @ResponseBody
    public String payTest(@RequestParam("payOrder") String payOrder) throws AlipayApiException {

        OrderEntity order = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", payOrder));
        PayVo payVo = new PayVo();
        if (order != null) {
            List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            List<String> collect = orderItems.stream().map(OrderItemEntity::getSkuName).collect(Collectors.toList());
            payVo.setBody(StringUtils.collectionToDelimitedString(collect, " + "));
            payVo.setSubject(order.getOrderSn());
            payVo.setOut_trade_no(order.getOrderSn());
            BigDecimal amount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
            payVo.setTotal_amount(amount.toString());
            return alipayTemplate.pay(payVo);
        }

        return null;
    }

//    @GetMapping("/payOrder")
//    public String paySuccess() {
//
//        return "";
//    }


}
